const express = require('express');
const jwt = require('jsonwebtoken');
const axios = require('axios');
const User = require('../models/User');
const { auth } = require('../middleware/auth');

const router = express.Router();

// 生成随机用户名
router.get('/generate-username', auth, async (req, res) => {
  try {
    let username;
    let attempts = 0;
    const maxAttempts = 10;
    
    do {
      username = User.generateRandomUsername();
      attempts++;
    } while (!(await User.isUsernameAvailable(username)) && attempts < maxAttempts);
    
    if (attempts >= maxAttempts) {
      return res.status(500).json({ message: '无法生成可用用户名，请稍后重试' });
    }
    
    res.json({ username });
  } catch (error) {
    console.error('生成用户名错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 检查用户名是否可用
router.post('/check-username', auth, async (req, res) => {
  try {
    const { username } = req.body;
    
    if (!username || username.length < 2) {
      return res.status(400).json({ message: '用户名至少需要2个字符' });
    }
    
    const isAvailable = await User.isUsernameAvailable(username);
    res.json({ isAvailable });
  } catch (error) {
    console.error('检查用户名错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 用户注册（简化版，只需要用户名）
router.post('/register', async (req, res) => {
  try {
    const { username, nickname } = req.body;
    
    if (!username) {
      return res.status(400).json({ message: '用户名不能为空' });
    }
    
    // 检查用户名是否可用
    const isAvailable = await User.isUsernameAvailable(username);
    if (!isAvailable) {
      return res.status(400).json({ message: '用户名已被使用' });
    }
    
    // 创建用户
    const user = new User({
      username,
      nickname: nickname || username,
      isOnline: true
    });
    
    await user.save();
    
    // 生成JWT token
    const token = jwt.sign(
      { userId: user._id },
      process.env.JWT_SECRET || 'your-secret-key',
      { expiresIn: '7d' }
    );
    
    res.status(201).json({
      message: '注册成功',
      token,
      user: {
        id: user._id,
        username: user.username,
        nickname: user.nickname,
        avatar: user.avatar
      }
    });
  } catch (error) {
    console.error('用户注册错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 用户登录（简化版，通过用户名）
router.post('/login', async (req, res) => {
  try {
    const { username } = req.body;
    
    if (!username) {
      return res.status(400).json({ message: '用户名不能为空' });
    }
    
    // 查找用户
    const user = await User.findOne({ username });
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    // 更新在线状态
    user.isOnline = true;
    user.lastSeen = new Date();
    await user.save();
    
    // 生成JWT token
    const token = jwt.sign(
      { userId: user._id },
      process.env.JWT_SECRET || 'your-secret-key',
      { expiresIn: '7d' }
    );
    
    res.json({
      message: '登录成功',
      token,
      user: {
        id: user._id,
        username: user.username,
        nickname: user.nickname,
        avatar: user.avatar,
        totalWins: user.totalWins,
        totalLosses: user.totalLosses,
        totalEarnings: user.totalEarnings
      }
    });
  } catch (error) {
    console.error('用户登录错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取用户信息
router.get('/profile', auth, async (req, res) => {
  try {
    const user = await User.findById(req.user.userId);
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    res.json({
      user: {
        id: user._id,
        username: user.username,
        nickname: user.nickname,
        avatar: user.avatar,
        isOnline: user.isOnline,
        lastSeen: user.lastSeen,
        totalWins: user.totalWins,
        totalLosses: user.totalLosses,
        totalEarnings: user.totalEarnings,
        createdAt: user.createdAt
      }
    });
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 更新用户信息
router.put('/profile', auth, async (req, res) => {
  try {
    const { nickname, avatar } = req.body;
    const user = await User.findById(req.user.userId);
    
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    // 更新字段
    if (nickname !== undefined) {
      user.nickname = nickname;
    }
    if (avatar !== undefined) {
      user.avatar = avatar;
    }
    
    await user.save();
    
    res.json({
      message: '更新成功',
      user: {
        id: user._id,
        username: user.username,
        nickname: user.nickname,
        avatar: user.avatar
      }
    });
  } catch (error) {
    console.error('更新用户信息错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 更新用户名
router.put('/username', auth, async (req, res) => {
  try {
    const { username } = req.body;
    const user = await User.findById(req.user.userId);
    
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    if (!username || username.length < 2) {
      return res.status(400).json({ message: '用户名至少需要2个字符' });
    }
    
    // 如果新用户名与当前用户名相同，直接允许更新
    if (username === user.username) {
      return res.json({
        message: '用户名未发生变化',
        user: {
          id: user._id,
          username: user.username,
          nickname: user.nickname
        }
      });
    }
    
  
    
    user.username = username;
    await user.save();
    
    res.json({
      message: '用户名更新成功',
      user: {
        id: user._id,
        username: user.username,
        nickname: user.nickname
      }
    });
  } catch (error) {
    console.error('更新用户名错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 用户登出
router.post('/logout', auth, async (req, res) => {
  try {
    const user = await User.findById(req.user.userId);
    if (user) {
      user.isOnline = false;
      user.lastSeen = new Date();
      await user.save();
    }
    
    res.json({ message: '登出成功' });
  } catch (error) {
    console.error('用户登出错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 微信小程序登录
router.post('/wechat-login', async (req, res) => {
  try {
    const { code } = req.body;
    
    if (!code) {
      return res.status(400).json({ message: '微信授权码不能为空' });
    }
    
    // 微信小程序配置
    const appid = process.env.WECHAT_APPID;
    const secret = process.env.WECHAT_SECRET;
    
    if (!appid || !secret) {
      console.error('微信小程序配置缺失');
      return res.status(500).json({ message: '服务器配置错误' });
    }
    
    // 调用微信API获取openid
    const wechatResponse = await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
      params: {
        appid,
        secret,
        js_code: code,
        grant_type: 'authorization_code'
      }
    });
    
    const { openid, session_key, errcode, errmsg } = wechatResponse.data;
    
    if (errcode) {
      console.error('微信API错误:', errcode, errmsg);
      return res.status(400).json({ message: '微信授权失败' });
    }
    
    if (!openid) {
      return res.status(400).json({ message: '无法获取微信用户标识' });
    }
    
    // 查找用户
    const user = await User.findOne({ wechatOpenId: openid });
    
    if (user) {
      // 用户已存在，直接登录
      user.isOnline = true;
      user.lastSeen = new Date();
      await user.save();
      
      // 生成JWT token
      const token = jwt.sign(
        { userId: user._id },
        process.env.JWT_SECRET || 'your-secret-key',
        { expiresIn: '7d' }
      );
      
      res.json({
        message: '微信登录成功',
        token,
        user: {
          id: user._id,
          username: user.username,
          nickname: user.nickname,
          avatar: user.avatar,
          totalWins: user.totalWins,
          totalLosses: user.totalLosses,
          totalEarnings: user.totalEarnings
        },
        isNewUser: false
      });
    } else {
      // 用户不存在，自动注册新用户
      const randomUsername = User.generateRandomUsername();
      
      // 确保用户名可用
      let finalUsername = randomUsername;
      let attempts = 0;
      const maxAttempts = 10;
      
      while (!(await User.isUsernameAvailable(finalUsername)) && attempts < maxAttempts) {
        finalUsername = User.generateRandomUsername();
        attempts++;
      }
      
      if (attempts >= maxAttempts) {
        return res.status(500).json({ message: '无法生成可用用户名，请稍后重试' });
      }
      
      // 创建新用户
      const newUser = new User({
        username: finalUsername,
        nickname: finalUsername,
        wechatOpenId: openid,
        isOnline: true
      });
      
      await newUser.save();
      
      // 生成JWT token
      const token = jwt.sign(
        { userId: newUser._id },
        process.env.JWT_SECRET || 'your-secret-key',
        { expiresIn: '7d' }
      );
      
      res.json({
        message: '微信登录成功（自动注册）',
        token,
        user: {
          id: newUser._id,
          username: newUser.username,
          nickname: newUser.nickname,
          avatar: newUser.avatar,
          totalWins: newUser.totalWins,
          totalLosses: newUser.totalLosses,
          totalEarnings: newUser.totalEarnings
        },
        isNewUser: true
      });
    }
  } catch (error) {
    console.error('微信登录错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});



module.exports = router; 